package com.bzxgc.sgwer.controller.project;

import com.bzxgc.sgwer.common.page.Constant;
import com.bzxgc.sgwer.common.util.JsonResult;
import com.bzxgc.sgwer.common.util.PageData;
import com.bzxgc.sgwer.entity.project.Project;
import com.bzxgc.sgwer.service.project.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @RequestMapping("/add")
    public String add() {
        return "project/save";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable("id") Long id, HttpServletRequest request) {
        Project project = projectService.getProjectById(id);
        request.setAttribute("project", project);
        return "project/save";
    }

    @RequestMapping("/ajax/save")
    @ResponseBody
    public JsonResult ajaxSave(Project project) {
        if (project.getId() == null) {
            projectService.addProject(project);
        } else {
            projectService.updateProject(project);
        }
        return JsonResult.success("保存成功");
    }

    @RequestMapping("/ajax/delete")
    @ResponseBody
    public JsonResult ajaxDelete(@RequestParam("ids") Long[] ids) {
        projectService.updateProjectStatus(ids, 2);
        return JsonResult.success("删除成功");
    }

    @RequestMapping("/ajax/update/status")
    @ResponseBody
    public JsonResult ajaxDelete(@RequestParam("ids") Long[] ids, @RequestParam("status") Integer status) {
        projectService.updateProjectStatus(ids, status);
        return JsonResult.success("操作成功");
    }

    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        int pageNum = Constant.DEFAULT_PAGE_NUM;
        String pageNumStr = request.getParameter("pageNum");
        if (pageNumStr != null && !pageNumStr.equals("")) {
            pageNum = Integer.parseInt(pageNumStr); // 显示第几页数据
        }

        int pageSize = Constant.DEFAULT_PAGE_SIZE;
        String pageSizeStr = request.getParameter("pageSize");
        if (pageSizeStr != null && !pageSizeStr.equals("")) {
            pageSize = Integer.parseInt(pageSizeStr); // 每页显示多少条记录
        }

        String name = request.getParameter("name");
        PageData<Project> pageData = projectService.getProjectListByPage(pageNum, pageSize, name);
        request.setAttribute("pageData", pageData);
        request.setAttribute("name", name);
        request.setAttribute("pageNum", pageNum);
        return "project/list";
    }
}
